package InternetTcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-10-11
 * Time: 17:01
 */
public class TcpEchoServer {
    //不同于Udp的DatagramSocket文件，ServerSocket文件负责揽活
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        //1：建立socket文件，并构造
        serverSocket = new ServerSocket(port);//导包抛异常
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //2:再建立一个Socket文件来进行连接通信（负责接待客户端）,可阻塞
            Socket clientSocket = serverSocket.accept();
            //3:写一个方法来处理这次连接，包括了收到请求和发出响应
            ExecutorService pool = Executors.newCachedThreadPool();

            pool.submit(new Runnable(){
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            /*
            Thread thread = new Thread(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();
            */

        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        //4:可以通过Socket文件获得客户端的ip和端口号
        System.out.printf("[%s , %d]客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        //5：循环读取请求和返回响应
        //Tcp是面向字节流，单位为字节,Socket本质就是文件，所以可以进行流操作
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            //6：while循环不断读取此次连接的请求并返回响应
            while(true){
                //7:读取操作
                /*
                byte[] buffer = new byte[1024];
                inputStream.read(buffer);//把读取到的请求放到数组里
                因为一会还要把这个请求转化为字符串，我们还有一个更简单拿到方法
                */

                //7：不要去放System.in输入，用（Socket对象）inputStream来帮助Scanner进行构造
                //   Scanner不仅可以从操作系统中读，也可以从文件，网络中读,Scanner放在while循环外也可以
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()){
                    System.out.printf("[%s , %d],客户端断开连接\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //8：根据请求计算响应
                String request = scanner.next();
                String response = process(request);
                //9:把响应返回给客户端（封装一下）,进行写入

                /*
                直接用write方法写回响应，不方便添加换行符\n，因为客户端在读取响应的时候使用next，结束标志为\n、空格、tab
                outputStream.write(response.getBytes(),0,response.getBytes().length);
                */
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s,%d] , request: %s , response : %s\n " ,clientSocket.getInetAddress(),clientSocket.getPort(),request,response);

            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();
        }

    }

    public String process(String response){
        return response;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
